var express = require('express');
var router = express.Router();
var model = require('../model');
var objectId = require('mongodb').ObjectID;
var crypto = require("crypto"); // 密码加密的处理
var multiparty = require('multiparty'); // 操作表单，图片上传
var fs = require('fs');
var nodemail = require('../routes/mail')

// 主页面
router.get('/', (req, res, next) => {
    model._Connect(db => {
        var authorname = req.sessionStore.authorname
        var authorImg = req.sessionStore.authorImg
        db.collection('author').find({ author: authorname }).toArray((error, result) => {
            if (result[0] == undefined) {
                result[0] = { motto: ["麻雀虽小，五脏俱全.", "前人栽树，后人乘凉.", "千丈麻绳，终须有结.", "宝镜磨清，只照一室；心镜磨清,可照六合."] }
            }
            authorImg ? authorImg : result[0].headImg
            res.render('index', { title: 'back_blog', mottoResult: result[0].motto, authorImg: authorImg, authorname: authorname });
        })
    })
})

// 登录页面
router.get('/login', (req, res, next) => {
    var authorname = req.sessionStore.authorname
    if (!authorname) {
        res.render('login', { title: '系统登录' });
    } else {
        res.redirect('/')
    }
})

// 登录接口
router.post('/login', (req, res, next) => {
    var authorname = req.body.author;
    var md5 = crypto.createHash("md5")
    var password = md5.update(req.body.password).digest("hex");
    var imgcodeNow = (req.body.imgcode).toLowerCase();
    var imgcodePrev = (req.sessionStore.imgcode).toLowerCase()
    if (!authorname) {
        res.status(200).json({ code: 0, msg: '用户名不能为空' });
    } else if (!req.body.password) {
        res.status(200).json({ code: 1, msg: '密码不能为空' })
    } else if (imgcodeNow != imgcodePrev) {
        res.status(200).json({ code: 2, msg: '验证码错误' })
    } else {
        model._Connect(db => {
            db.collection('author').find({ author: authorname }).toArray((error, result) => {
                if (error) throw error;
                else if (!result || result.length == 0) {
                    res.status(200).json({ code: 3, msg: "用户不存在，请联系站长" });
                } else if (authorname == "admin") {
                    req.sessionStore.authorname = authorname
                    req.sessionStore.authorImg = result[0].headImg
                    res.status(200).json({ code: 6, msg: "欢迎你" + authorname });
                } else {
                    if (password != result[0].password) {
                        res.status(200).json({ code: 4, msg: "用户密码错误" });
                    } else {
                        req.sessionStore.authorname = authorname
                        req.sessionStore.authorImg = result[0].headImg
                        res.status(200).json({ code: 5, msg: "欢迎你" + authorname });
                    }
                }
            })
        })
    }
})

// 发送邮件
router.post('/sendemail', (req, res, next) => {
    var email = req.body.email
    let emailCode = ""; //验证码为6位随机数
    while (emailCode.length < 6) {
        emailCode += Math.floor(Math.random() * 10);
    }
    req.sessionStore.emailCode = emailCode;
    req.sessionStore.email = email;
    var mail = {
        from: 'cds@likepoems.com', // 发件人地址
        to: email, // 收件人地址
        subject: '个人博客邮件提醒', // 邮件标题
        html: `
            <div class = "messagebox" 
                style=" background-color: #eef2fa;
                border: 1px solid #d8e3e8;
                font-size: 15px;
                color: #111;
                padding: 0 15px;
                border-radius: 5px;
                -moz-border-radius: 5px;
                -webkit-border-radius: 5px;">
                <p>亲爱的Master,您的验证码是<strong style="color: #ff4e2a;"> ${emailCode} </strong></p>
                <p>仅用于博客后台系统验证,请勿告知其他Master噢!</p>
            </div>` // html 内容
    };
    nodemail(mail)
})

// 用户注册
router.post('/signin', (req, res, next) => {
    var authorname = req.body.author;
    var email = req.body.email // 获取的邮箱
    var yzm = req.body.yzm  // 获取的验证码
    var emailCode = req.sessionStore.emailCode
    var md5 = crypto.createHash("md5")
    var pwd1 = req.body.pwd1
    var pwd2 = req.body.pwd2
    var password = md5.update(pwd2).digest("hex");
    var userdata = {
        author: authorname,
        password: password,
        email: email,
        motto: ["step into the ocean of knowledge.", "an apple a day keeps the doctor alway."],
        headImg: "/upload/authors/user.jpg"
    }
    if (!authorname) {
        res.status(200).json({ code: 0, msg: '请输入用户名' });
    } else if (!email) {
        res.status(200).json({ code: 1, msg: "请输入邮箱" });
    } else if (!yzm) {
        res.status(200).json({ code: 2, msg: "请输入验证码" });
    } else if (yzm != emailCode) {
        res.status(200).json({ code: 3, msg: '验证码错误' })
    } else if (!pwd1 || !pwd2) {
        res.status(200).json({ code: 4, msg: '请输入密码' })
    } else if (pwd1 !== pwd2) {
        res.status(200).json({ code: 5, msg: '输入的密码不一致' })
    } else {
        model._Connect(db => {
            db.collection('author').find({ author: authorname }).toArray((error, result) => {
                if (error) throw error
                else if (result.length !== 0) {
                    res.status(200).json({ code: 6, msg: '用户名已存在,请换一个吧！' });
                } else {
                    model._Connect(db => {
                        db.collection('author').insertOne(userdata, (error, result) => {
                            if (error) {
                                res.status(200).json({ code: 7, msg: "账号创建失败" });
                            } else {
                                res.status(200).json({ code: 8, msg: "账号创建成功" });
                                req.sessionStore.emailCode = null
                            }
                        })
                    })
                }
            })
        })
    }
})

// 重置密码
router.post('/resetpwd', (req, res, next) => {
    var author = req.body.author
    var yzm = req.body.yzm  // 获取的验证码
    var mail = req.body.email
    var email = req.sessionStore.email
    var emailCode = req.sessionStore.emailCode
    var md5 = crypto.createHash("md5")
    var password = md5.update(req.body.pwd).digest("hex");
    var updDateData = { $set: { password: password } };
    if (!mail) {
        res.status(200).json({ code: 0, msg: "请输入邮箱" });
    } else if (mail != email) {
        res.status(200).json({ code: 1, msg: "请刷新页面再进行操作" });
    } else if (!yzm) {
        res.status(200).json({ code: 2, msg: "请输入验证码" });
    } else if (!req.body.pwd) {
        res.status(200).json({ code: 3, msg: '请输入密码' })
    } else if (yzm != emailCode) {
        res.status(200).json({ code: 4, msg: '验证码输入错误，请重新输入' })
    } else {
        model._Connect(db => {
            db.collection('author').find({ author: author, email: mail }).toArray((err, result) => {
                if (err) throw err;
                else if (!result || result.length == 0) {
                    res.status(200).json({ code: 5, msg: "账号邮箱不存在或填写错误" });
                } else {
                    model._Connect(db => {
                        db.collection('author').updateOne({ author }, updDateData, (error, result2) => {
                            if (error) {
                                res.status(200).json({ code: 6, msg: "密码重置失败" });
                            } else {
                                req.sessionStore.emailCode = null
                                res.status(200).json({ code: 7, msg: "密码重置成功" });
                            }
                        })
                    })
                }
            })
        })
    }
})

// 注销登录
router.get('/logout', (req, res, next) => {
    req.sessionStore.authorname = null
    req.sessionStore.authorImg = null
    req.sessionStore.emailCode = null
    res.redirect('/login')
})


// 用户管理
router.get('/manageauthors', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var page = req.query.page || 1
    var userlist = {
        total: 0,
        curPage: page,
        list: []
    }
    var pageSize = 2
    if (authorname == "admin") {
        model._Connect(db => {
            db.collection('author').find().toArray((error, result) => {
                userlist.total = Math.ceil(result.length / pageSize)
                model._Connect(db => {
                    db.collection('author').find().limit(pageSize).skip((page - 1) * pageSize).toArray((error2, result2) => {
                        if (result2.length == 0) {
                            res.redirect('/manageauthors?page=' + ((page - 1) || 1))
                        } else {
                            userlist.list = result2
                            res.render('manageauthors', { title: '用户管理', userlist: userlist, authorImg: authorImg, authorname: authorname });
                        }
                    })
                })
            })
        })
    } else {
        res.send('<script>alert("你不是管理员，无权限查看");history.back(-1)</script>')
    }

})

// 获取用户信息
router.get('/authorinfo', (req, res, next) => {
    var authorname = req.sessionStore.authorname
    var authorImg = req.sessionStore.authorImg
    model._Connect(db => {
        db.collection('author').find({ author: authorname }).toArray((error, result) => {
            res.render('authorinfo', { title: '用户信息', authorResult: result[0], authorImg: authorImg, authorname: authorname });
        })
    })
})

// 添加用户(管理员)
router.post('/addauthor', (req, res, next) => {
    var authorname = req.body.author;
    var email = req.body.email // 获取的邮箱
    var md5 = crypto.createHash("md5")
    var pwd = req.body.password
    var password = md5.update(pwd).digest("hex");
    var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/g;//邮箱验证
    var userdata = {
        author: authorname,
        password: password,
        email: email,
        motto: ["step into the ocean of knowledge.", "an apple a day keeps the doctor alway."],
        headImg: "/upload/authors/user.jpg"
    }
    if (!authorname || authorname == "admin") {
        res.status(200).json({ code: 0, msg: '请输入用户名' });
    } else if (!email) {
        res.status(200).json({ code: 1, msg: "请输入邮箱" });
    } else if (!reg.test(email)) {
        res.status(200).json({ code: 2, msg: "邮箱格式不正确" });
    } else if (!pwd) {
        res.status(200).json({ code: 3, msg: '请输入密码' })
    } else {
        model._Connect(db => {
            db.collection('author').find({ author: authorname }).toArray((error, result) => {
                if (error) throw error
                else if (result.length !== 0) {
                    res.status(200).json({ code: 4, msg: '用户名已存在,请换一个吧！' });
                } else {
                    model._Connect(db => {
                        db.collection('author').insertOne(userdata, (error2, result2) => {
                            if (error2) {
                                res.status(200).json({ code: 5, msg: "账号创建失败" });
                            } else {
                                res.status(200).json({ code: 6, msg: "账号创建成功" });
                            }
                        })
                    })
                }
            })
        })
    }
})

// 用户信息修改路由
router.get('/editauthorinfo', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var authorid = objectId(req.query.id)
    var page = req.query.page
    model._Connect(db => {
        db.collection('author').find({ _id: authorid }).toArray((error, result) => {
            res.render('editauthorinfo', { title: '用户信息修改', authorinfos: result[0], page: page, authorImg: authorImg, authorname: authorname });
        })
    })
})

// 用户信息修改逻辑(普通用户)
router.post('/updateauthorinfo', (req, res, next) => {
    let form = new multiparty.Form({
        uploadDir: 'public/upload/authors' // 定义图片上传的根目录
    });
    var emailCode = req.sessionStore.emailCode
    // 获取参数并处理
    form.parse(req, (err, fields, files) => {
        var _id = objectId(fields.authorid[0]);
        var motto = fields.motto[0].split(',')
        var author = fields.authorname[0]
        var email = fields.email[0]
        var yzm = fields.yzm[0]
        var md5_1 = crypto.createHash("md5")
        var md5_2 = crypto.createHash("md5")
        var oldpassword = md5_1.update(fields.password[0]).digest("hex");
        var password = md5_2.update(fields.password2[0]).digest("hex");
        var filePath = files.headImg[0].path // 头像图片的原始路径
        var basePath = "public/upload/authors/"
        var newFilePath = basePath + "author_" + files.headImg[0].originalFilename;
        var headImg = newFilePath.replace("public", "") // 新头像名称
        var authoroldimg = fields.authoroldimg[0] // 原头像名称
        if (fs.existsSync(basePath) && files.headImg[0].size !== 0) {
            fs.rename(filePath, newFilePath, (err) => {
                if (err) throw err
            })
        } else {
            headImg = authoroldimg
        }

        // 组装数据
        var updDateData = { $set: { _id, author, password, email, motto, headImg } };
        if (!author || !oldpassword || !fields.password2[0] || !motto || !email || !yzm) {
            res.status(200).json({ code: 1, msg: "输入的内容不能为空" });
        } else if (yzm !== emailCode) {
            res.status(200).json({ code: 2, msg: "验证码错误" });
        } else {
            model._Connect(db => {
                db.collection('author').findOne({ _id }, (err, result) => {
                    if (oldpassword != result.password) {
                        res.status(200).json({ code: 3, msg: "原密码错误" });
                    } else if (oldpassword == password) {
                        res.status(200).json({ code: 4, msg: "新密码不能和原密码相同" });
                    } else {
                        model._Connect(db => {
                            db.collection('author').updateOne({ _id }, updDateData, (error, result2) => {
                                if (error) {
                                    res.status(200).json({ code: 5, msg: "用户信息更新失败" });
                                } else {
                                    req.sessionStore.authorname = null
                                    req.sessionStore.emailCode = null
                                    res.status(200).json({ code: 6, msg: "用户信息更新成功" });
                                }
                            })
                        })
                    }
                })
            })
        }
    })
})

// 用户信息修改逻辑(管理员)
router.post('/editauthorinfo', (req, res, next) => {
    let form = new multiparty.Form({
        uploadDir: 'public/upload/authors' // 定义图片上传的根目录
    });
    // 获取参数并处理
    form.parse(req, (err, fields, files) => {
        var _id = objectId(fields.authorid[0]);
        var motto = fields.motto[0].split(',')
        var author = fields.authorname[0]
        var email = fields.email[0]
        var md5 = crypto.createHash("md5")
        var password = md5.update(fields.password[0]).digest("hex");
        var filePath = files.headImg[0].path // 头像图片的原始路径
        var basePath = "public/upload/authors/"
        var newFilePath = basePath + "author_" + files.headImg[0].originalFilename;
        var headImg = newFilePath.replace("public", "") // 新头像名称
        var authoroldimg = fields.authoroldimg[0] // 原头像名称
        if (fs.existsSync(basePath) && files.headImg[0].size !== 0) {
            fs.rename(filePath, newFilePath, (err) => {
                if (err) throw err
            })
        } else {
            headImg = authoroldimg
        }

        // 组装数据
        var updDateData = { $set: { _id, author, password, email, motto, headImg } };
        if (!author || !fields.password[0] || !motto || !email) {
            res.status(200).json({ code: 0, msg: "无效字符" });
        } else {
            model._Connect(db => {
                db.collection('author').updateOne({ _id }, updDateData, (error, result2) => {
                    if (error) {
                        res.status(200).json({ code: 1, msg: "操作失败" });
                    } else {
                        res.status(200).json({ code: 2, msg: "操作成功" });
                    }
                })
            })
        }
    })
})

// 删除用户账号
router.get('/deleteauthor', (req, res, next) => {
    var id = objectId(req.query.id)
    var page = req.query.page
    var authorname = req.sessionStore.authorname
    if (authorname != "admin") {
        res.status(200).json({ code: 8, msg: "你无权限进行操作" });
    } else {
        model._Connect(db => {
            db.collection('author').deleteOne({ _id: id }, (error, result) => {
                if (error) {
                    res.status(200).json({ code: 1, msg: "用户删除失败" });
                } else {
                    res.status(200).json({ code: 2, msg: "用户删除成功" });
                }
            })
        })
    }

})

// 博客类别管理
router.get('/manageclassify', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var page = req.query.page || 1
    var classifydata = {
        total: 0,
        curPage: page,
        list: []
    }
    var pageSize = 5
    model._Connect(db => {
        db.collection('classify').find().toArray((error, result) => {
            classifydata.total = Math.ceil(result.length / pageSize)
            model._Connect(db => {
                db.collection('classify').find().limit(pageSize).skip((page - 1) * pageSize).toArray((error2, result2) => {
                    if (result2.length == 0) {
                        res.redirect('/manageclassify?page=' + ((page - 1) || 1))
                    } else {
                        classifydata.list = result2
                        res.render('manageclassify', { title: '博客分类管理', classifydata: classifydata, authorImg: authorImg, authorname: authorname });
                    }
                })
            })
        })
    })
})
// 博客类别添加路由
router.get('/addclassify', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var page = req.query.page
    res.render('addclassify', { title: '博客类别添加', page: page, authorImg: authorImg, authorname: authorname });
})
// 博客类别添加
router.post('/addclassify', (req, res, next) => {
    let form = new multiparty.Form({
        uploadDir: 'public/upload/classify'
    });
    // 获取参数并处理
    form.parse(req, (err, fields, files) => {
        var filePath = files.classifyimg[0].path // 图片的原始路径
        var basePath = "public/upload/classify/"
        var newFilePath = basePath + "classify_" + files.classifyimg[0].originalFilename;
        var classifyImg = newFilePath.replace("public", "")
        if (fs.existsSync(basePath)) {
            fs.rename(filePath, newFilePath, (err) => {
                if (err) throw err
            })
        }
        var classifydata = {
            classify: fields.classify[0],
            classifyImg: classifyImg
        }
        if (!classifydata.classify) {
            res.status(200).json({ code: 0, msg: "输入的内容不能为空" });
        } else if (!files.classifyimg[0].originalFilename) {
            res.status(200).json({ code: 1, msg: '请上传博客类别图片' })
        } else {
            model._Connect(db => {
                db.collection('classify').insertOne(classifydata, (error, result2) => {
                    if (error) {
                        res.status(200).json({ code: 2, msg: "博客类别添加失败" });
                    } else {
                        res.status(200).json({ code: 3, msg: "博客类别添加成功" });
                    }
                })
            })
        }
    })
})
// 博客类别修改路由
router.get('/editclassify', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var blogid = objectId(req.query.id)
    var page = req.query.page
    model._Connect(db => {
        db.collection('classify').find({ _id: blogid }).toArray((error, result) => {
            res.render('editclassify', { title: '博客类别修改', editclassify: result[0], page: page, authorImg: authorImg, authorname: authorname });
        })
    })
})

// 博客类别修改
router.post('/updateclassify', (req, res, next) => {
    var authorname = req.sessionStore.authorname
    let form = new multiparty.Form({
        uploadDir: 'public/upload/classify'
    });
    if (authorname != "admin") {
        res.status(200).json({ code: 8, msg: "你无权限进行操作" });
    } else {
        // 获取参数并处理
        form.parse(req, (err, fields, files) => {
            console.log(fields);
            var _id = objectId(fields.classifyid[0]);
            var classify = fields.classify[0]
            var filePath = files.newimg[0].path // 图片的原始路径
            var basePath = "public/upload/classify/"
            var newFilePath = basePath + "classify_" + files.newimg[0].originalFilename;
            var classifyImg = newFilePath.replace("public", "")
            var classifyoldimg = fields.oldimg[0] // 原头像名称
            if (fs.existsSync(basePath) && files.newimg[0].size !== 0) {
                fs.rename(filePath, newFilePath, (err) => {
                    if (err) throw err
                })
            } else {
                classifyImg = classifyoldimg
            }
            // 组装数据
            var updDateData = { $set: { _id, classify, classifyImg } };
            if (!classify) {
                res.status(200).json({ code: 0, msg: "输入的内容不能为空" });
            } else {
                model._Connect(db => {
                    db.collection('classify').updateOne({ _id }, updDateData, (error, result2) => {
                        if (error) {
                            res.status(200).json({ code: 1, msg: "博客类别更新失败" });
                        } else {
                            res.status(200).json({ code: 2, msg: "博客类别更新成功" });
                        }
                    })
                })
            }
        })
    }
})
// 博客分类删除
router.get('/deleteclassify', (req, res, next) => {
    var id = objectId(req.query.id)
    var page = req.query.page
    var authorname = req.sessionStore.authorname
    if (authorname != "admin") {
        res.status(200).json({ code: 8, msg: "你无权限进行操作" });
    } else {
        model._Connect(db => {
            db.collection('classify').deleteOne({ _id: id }, (error, result) => {
                if (error) {
                    res.status(200).json({ code: 1, msg: "博客分类删除失败" });
                } else {
                    res.status(200).json({ code: 2, msg: "博客分类删除成功" });
                }
            })
        })
    }

})

// 写博客路由
router.get('/writeblogs', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    model._Connect(db => {
        db.collection('classify').find().toArray((error, result) => {
            res.render('writeblog', { title: '写博客', blogclassify: result, authorImg: authorImg, authorname: authorname });
        })
    })
})
// 写博客逻辑
router.post('/writeblogs', (req, res, next) => {
    function settime(time = +new Date()) {   // 增加8小时
        var date = new Date(time + 8 * 3600 * 1000);
        return date.toJSON().substr(0, 19).replace('T', ' ');
    }
    let form = new multiparty.Form({
        uploadDir: 'public/upload/pages/images'
    });
    // 获取参数并处理
    form.parse(req, (err, fields, files) => {
        var filePath = files.classifyimg[0].path // 图片的原始路径
        var basePath = "public/upload/pages/images/"
        var newFilePath = basePath + "pages_" + files.classifyimg[0].originalFilename;
        var cover = newFilePath.replace("public", "")
        if (fs.existsSync(basePath)) {
            fs.rename(filePath, newFilePath, (err) => {
                if (err) throw err
            })
        }
        var blogdata = {
            title: fields.title[0],
            author: req.sessionStore.authorname,
            pageview: 0,
            category: fields.classify[0],
            editorvalue: fields.editorValue[0],
            createtime: settime(),
            cover: cover
        }
        if (!blogdata.title) {
            res.status(200).json({ code: 1, msg: "请添加博客标题" });
        } else if (!blogdata.author) {
            res.status(200).json({ code: 2, msg: '请添加博客作者' })
        } else if (!blogdata.category) {
            res.status(200).json({ code: 3, msg: '请选择博客类型' })
        } else if (!files.classifyimg[0].size || files.classifyimg[0].size == 0) {
            res.status(200).json({ code: 6, msg: '请选添加博客封面' })
        } else {
            model._Connect(db => {
                db.collection('essay').insertOne(blogdata, (error, result) => {
                    if (error) {
                        res.status(200).json({ code: 4, msg: "发布失败" });
                    } else {
                        res.status(200).json({ code: 5, msg: "发布成功" });
                    }
                })
            })
        }
    })

})

// 博客管理页面
router.get('/manageblogs', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var page = req.query.page || 1
    var blogdata = {
        total: 0,
        curPage: page,
        list: []
    }
    var pageSize = 5
    model._Connect(db => {
        if (authorname == "admin") {
            db.collection('essay').find().toArray((error, result) => {
                blogdata.total = Math.ceil(result.length / pageSize)
                model._Connect(db => {
                    db.collection('essay').find().limit(pageSize).skip((page - 1) * pageSize).toArray((error2, result2) => {
                        if (result2.length == 0) {
                            res.redirect('/manageblogs?page=' + ((page - 1) || 1))
                        } else {
                            blogdata.list = result2
                            res.render('manageblogs', { title: '博客管理', blogdata: blogdata, authorImg: authorImg, authorname: authorname });
                        }
                    })
                })
            })
        } else {
            db.collection('essay').find({ author: authorname }).toArray((error, result) => {
                blogdata.total = Math.ceil(result.length / pageSize)
                if (result.length == 0) {
                    res.send('<script>alert("你还没有写任何博客哦");history.back(-1)</script>')
                } else {
                    model._Connect(db => {
                        db.collection('essay').find({ author: authorname }).limit(pageSize).skip((page - 1) * pageSize).toArray((error2, result2) => {
                            if (result2.length == 0) {
                                res.redirect('/manageblogs?page=' + ((page - 1) || 1))
                            } else {
                                blogdata.list = result2
                                res.render('manageblogs', { title: '博客管理', blogdata: blogdata, authorImg: authorImg, authorname: authorname });
                            }
                        })
                    })
                }
            })
        }
    })
})

// 博客修改路由
router.get('/editblogs', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var blogid = objectId(req.query.id)
    var page = req.query.page
    model._Connect(db => {
        db.collection('essay').find({ _id: blogid }).toArray((error, result) => {
            res.render('editblogs', { title: '博客修改', editblog: result[0], page: page, authorImg: authorImg, authorname: authorname });
        })
    })
})
// 博客修改逻辑
router.post('/editblogs', (req, res, next) => {
    var authorname = req.sessionStore.authorname
    function settime(time = +new Date()) {// 增加8小时
        var date = new Date(time + 8 * 3600 * 1000);
        return date.toJSON().substr(0, 19).replace('T', ' ');
    }
    let form = new multiparty.Form({
        uploadDir: 'public/upload/classify'
    });
    // 获取参数并处理
    form.parse(req, (err, fields, files) => {
        var blogid = objectId(fields.blogid[0])
        var page = fields.blogpage[0]
        var filePath = files.classifyimg[0].path // 图片的原始路径
        var basePath = "public/upload/pages/images/"
        var newFilePath = basePath + "pages_" + files.classifyimg[0].originalFilename;
        var cover = newFilePath.replace("public", "") // 博客新封面
        var oldcover = fields.oldimg[0] // 博客原封面
        if (fs.existsSync(basePath) && files.classifyimg[0].size !== 0) {
            fs.rename(filePath, newFilePath, (err) => {
                if (err) throw err
            })
        } else {
            cover = oldcover
        }
        var title = fields.title[0];
        var author = authorname;
        var category = (fields.category[0]).split(','); // 用户选择的博客类别
        var editorvalue = fields.editorValue[0];
        var createtime = settime();
        model._Connect(db => {
            db.collection('classify').find().toArray((error, result) => {
                let allcategory = result.map((obj, index) => { return (obj.classify).toLowerCase() }).join(",").split(',') // 数据库中的博客类别
                const fn = (category, allcategory) => category.filter(item => !allcategory.includes(item.toLowerCase()))
                var tips = (fn(category, allcategory)).toString();
                if (!title) {
                    res.status(200).json({ code: 1, msg: "请添加博客标题" });
                } else if (!author) {
                    res.status(200).json({ code: 2, msg: '请添加博客作者' })
                } else if (!fields.category[0]) {
                    res.status(200).json({ code: 3, msg: '请添加博客类型' })
                } else if (tips) {
                    res.status(200).json({ code: 6, msg: tips + '' + '类别不存在于数据库中' })
                } else if (!cover) {
                    res.status(200).json({ code: 7, msg: '请添加博客封面' })
                } else {
                    model._Connect(db => {
                        db.collection('essay').updateOne({ _id: blogid }, { $set: { title: title, author: author, category: fields.category[0], editorvalue: editorvalue, createtime: createtime, cover: cover } }, (error, result) => {
                            if (error) {
                                res.status(200).json({ code: 4, msg: "博客修改失败" });
                            } else {
                                res.status(200).json({ code: 5, msg: "博客修改成功" });
                            }
                        })
                    })
                }
            })
        })
    })
})

// 博客删除
router.get('/deleteblogs', (req, res, next) => {
    var id = objectId(req.query.id)
    var page = req.query.page
    var authorname = req.sessionStore.authorname
    model._Connect(db => {
        db.collection('essay').deleteOne({ _id: id, author: authorname }, (error, result) => {
            if (error) {
                res.status(200).json({ code: 1, msg: "博客删除失败" });
            } else {
                res.status(200).json({ code: 2, msg: "博客删除成功" });
            }
        })
    })

})


// 用户留言获取
router.get('/peopleleaveword', (req, res, next) => {
    var authorImg = req.sessionStore.authorImg
    var authorname = req.sessionStore.authorname
    var page = req.query.page || 1
    var liuyandata = {
        total: 0,
        curPage: page,
        list: []
    }
    var pageSize = 4
    if (authorname == "admin") {
        model._Connect(db => {
            db.collection('liuyan').find().toArray((error, result) => {
                liuyandata.total = Math.ceil(result.length / pageSize)
                model._Connect(db => {
                    db.collection('liuyan').find().limit(pageSize).skip((page - 1) * pageSize).toArray((error2, result2) => {
                        if (result2.length == 0) {
                            res.redirect('/peopleleaveword?page=' + ((page - 1) || 1))
                        } else {
                            liuyandata.list = result2
                            res.render('peopleleaveword', { title: '用户留言', liuyandata: liuyandata, authorImg: authorImg, authorname: authorname });
                        }
                    })
                })
            })
        })
    } else {
        res.send('<script>alert("你不是管理员，无权限查看");history.back(-1)</script>')
    }
})

// 用户留言删除
router.get('/deleteliuyan', (req, res, next) => {
    var blogid = objectId(req.query.id)
    var page = req.query.page
    var authorname = req.sessionStore.authorname
    if (authorname != "admin") {
        res.status(200).json({ code: 8, msg: "你无权限进行操作" });
    } else {
        model._Connect(db => {
            db.collection('liuyan').deleteOne({ _id: blogid }, (error, result) => {
                if (error) {
                    res.status(200).json({ code: 1, msg: "用户留言删除失败" });
                } else {
                    res.status(200).json({ code: 2, msg: "用户留言删除成功" });
                }
            })
        })
    }

})

// 定义获取博客文章的数据接口
router.get('/getessay', (req, res) => {
    let { pageSize, currentPage } = req.query;
    pageSize = pageSize ? pageSize : 3;
    currentPage = currentPage ? currentPage : 1;
    model._Connect(db => {
        db.collection('essay').find().toArray((error, result) => {
            if (error) throw error
            let total = result.length
            model._Connect(db => {
                db.collection('essay').find({}, { author: 0, pageview: 0 }).limit(parseInt(pageSize)).skip((parseInt(currentPage) - 1) * parseInt(pageSize)).toArray((error2, result2) => {
                    if (error2) throw error2;
                    let data = result2
                    res.send({ total, data });
                })
            })
        });
    })
});
// 定义获取一篇博客文章的接口
router.get('/getessaybyid', (req, res) => {
    var pageid = objectId(req.query.pageid); // 文章的id
    console.log(pageid);
    model._Connect(db => {
        db.collection('essay').find({ _id: pageid }).toArray((error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        })
    })
})
router.get('/getessaybytag', (req, res) => {
    var pagetag = req.query.pagetag; // 文章标签
    console.log(pagetag);
    model._Connect(db => {
        db.collection('essay').find({ category: pagetag }).toArray((error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        })
    })
})

// 定义获取最新博客文章的数据接口
router.get('/getlatestessay', (req, res) => {
    model._Connect(db => {
        db.collection('essay').find().toArray((error, result) => {
            if (error) throw error
            let totalpages = result.length
            model._Connect(db => {
                db.collection('essay').find().sort({ "_id": -1 }).limit(5).toArray((error2, result2) => {
                    if (error2) throw error2;
                    let data = result2
                    model._Connect(db => {
                        db.collection('classify').find().toArray((error3, result3) => {
                            if (error3) throw error3;
                            let totalclassify = result3.length
                            res.send({ totalpages, totalclassify, data });
                        })
                    })

                })
            })
        });
    })
});

// 定义获取博客分类的数据接口
router.get('/getclassify', (req, res) => {
    model._Connect(db => {
        db.collection('classify').find().toArray((error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        });
    })
});

// 定义获取博客留言的数据接口
router.get('/getliuyan', (req, res) => {
    model._Connect(db => {
        db.collection('liuyan').find().toArray((error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        });
    })
});

// 定义写留言的数据接口
router.post('/writeliuyan', (req, res, next) => {
    function settime(time = +new Date()) {  // 增加8小时
        var date = new Date(time + 8 * 3600 * 1000);
        return date.toJSON().substr(0, 19).replace('T', ' ');
    }
    let website = req.body.website
    let reg = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/
    if (!reg.test(website)) {
        website = 'test.iamflame.top'
    }
    var liuyandata = {
        visitor: req.body.visitor,
        mail: req.body.mail,
        website: website,
        content: req.body.content,
        time: settime()
    }
    model._Connect(db => {
        db.collection('liuyan').insertOne(liuyandata, (error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        })
    })
})


// 文章检索
router.get('/searchpages', (req, res, next) => {
    let searchKey = req.query.searchKey
    model._Connect(db => {
        db.collection('essay').find({ $text: { $search: searchKey } }).toArray((error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        });
    })
})



// 刷新文章访问量
router.post('/pageview', (req, res, next) => {
    // console.log(req.body.pageview) // 阅读量
    var pageid = objectId(req.body.pageid);
    model._Connect(db => {
        db.collection('essay').update({ "_id": pageid }, { "$inc": { "pageview": 1 } }, (error, result) => {
            if (error) throw error
            res.send(JSON.stringify(result));
        })
    })
})

module.exports = router;
